import { login, logout } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { isHttp, isEmpty } from "@/utils/validate"
import defAva from '@/assets/images/profile.jpg'
import router, { constantRoutes, dynamicRoutes } from '@/router'
// 定义缓存用户信息的键名
const USER_INFO_KEY = 'user_info'

// 从 localStorage 获取缓存的用户信息
const getCachedUserInfo = () => {
  const userInfo = localStorage.getItem(USER_INFO_KEY)
  return userInfo ? JSON.parse(userInfo) : null
}

// 将用户信息存入 localStorage
const setCachedUserInfo = (userInfo) => {
  localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfo))
}

// 移除缓存的用户信息
const removeCachedUserInfo = () => {
  localStorage.removeItem(USER_INFO_KEY)
}
const useUserStore = defineStore(
  'user',
  {
    state: () => {
      //尝试从缓存中获取用户信息
      const cachedUserInfo = getCachedUserInfo()
      return {
        token: getToken(),
        id: cachedUserInfo?.id || '',
        name: cachedUserInfo?.name || '',
        nickname: cachedUserInfo?.nickname || '',
        // avatar: cachedUserInfo?.avatar || '',
        roles: cachedUserInfo?.roles || [],
        permissions: cachedUserInfo?.permissions || ["*"],
        devices: cachedUserInfo?.devices || {},
      }
    },
    actions: {
      // 登录
      login(userInfo) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        return new Promise((resolve, reject) => {
          login(username, password).then(res => {
            setToken(res.token)
            this.token = res.token
            this.name = res.userInfo.username
            this.nickname = res.userInfo.nickname
            this.roles = res.roles;
            this.devices = res.devices;
            this.id = res.userInfo.id
            // 缓存用户信息
            setCachedUserInfo({
              id: this.id,
              name: this.name,
              nickname: this.nickname,
              // avatar: this.avatar,
              devices: this.devices,
              roles: this.roles,
              permissions: this.permissions
            })
            
            // this.roles = []
            // this.permissions = 
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息

      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          // logout(this.token).then(() => {
          this.token = ''
          this.roles = []
          this.permissions = []
          // 移除缓存的用户信息
          removeCachedUserInfo()
          removeToken()
          resolve()
          // }).catch(error => {
          //   reject(error)
          // })
        })
      }
    }
  })

export default useUserStore
